import * as types from '../mutations-types'
import shop from '../../api/shop'

export default {
  state: {
    all: [],
    firstLoaded: false,
    isLoading: false
  },
  actions: {
    getAllProducts ({commit, state}) {
      state.isLoading = true
      shop.getProducts(products => {
        state.isLoading = false
        state.firstLoaded = true
        commit(types.RECEIVE_PRODUCTS, { products })
      })
    }
  },
  mutations: {
    [types.RECEIVE_PRODUCTS] (state, { products }) {
      state.all = products
    },
    [types.ADD_TO_CART] (state, { id }) {
      const record = state.all.find(p => p.id === id)
      if (record && record.inventory > 0) {
        record.inventory--
      }
    },
    [types.REMOVE_FROM_CART] (state, { id }) {
      const record = state.all.find(p => p.id === id)
      if (record) {
        record.inventory++
      }
    }
  },
  getters: {
    allProducts: (state) => state.all,
    isLoading: (state) => state.isLoading,
    firstLoaded: (state) => state.firstLoaded,
    getProductById: (state, getters) => (id) => {
      return state.all.find(p => p.id === id)
    },
    getProductByType: (state, getters) => (typeId) => {
      if (!isNaN(typeId)) {
        return state.all.filter(p => p.type === parseInt(typeId))
      } else {
        return []
      }
    }
  }
}
